package com.blame.onlinemusicserver.service;

import com.blame.onlinemusicserver.mapper.LoveMusicMapper;
import com.blame.onlinemusicserver.mapper.MusicMapper;
import com.blame.onlinemusicserver.model.Music;
import com.blame.onlinemusicserver.model.User;
import com.blame.onlinemusicserver.tools.Constant;
import com.blame.onlinemusicserver.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MusicService {

    @Value("${spring.music.local.path}")
    private String SAVE_PATH;

    @Autowired
    private MusicMapper mapper;

    @Autowired
    private LoveMusicMapper loveMusicMapper;

    //添加音乐
    public ResponseBodyMessage<Boolean> insertMusic(String singer,
                                                     MultipartFile file,
                                                     HttpServletRequest request,
                                                     HttpServletResponse response){
        //1.检查登录
        HttpSession session=request.getSession(false);
        if(session==null || session.getAttribute(Constant.USERINFO_SESSION_KEY)==null){
            log.error("未登录，请先进行登录");
            return new ResponseBodyMessage<>(0,"没有登录",false);

        }
        //2.检查数数据库中是否有此音乐
        //得到文件的名字和类型
        String fileNameAndType=file.getOriginalFilename();
        System.out.println("fileNameAndType"+fileNameAndType);

        //根据文件的拓展名来判断是否为.MP3文件
        String extension=fileNameAndType.substring(fileNameAndType.lastIndexOf(".")).toLowerCase();
        if(!extension.equals(".mp3")){
            return new ResponseBodyMessage<>(-0,"只支持MP3文件上传",false);
        }
        //根据MINE判断
        try {
            String mimeType=file.getContentType();
            log.info("文件的MINI类型:{}",mimeType);
            if(mimeType==null || !mimeType.equals("audio/mpeg")){
                return new ResponseBodyMessage<>(0,"文件格式不正确,只支持MP3音频上传",false);
            }
        }catch (Exception e){
            log.error("文件检验异常:{}",e.getMessage());
            return new ResponseBodyMessage<>(0,"文件类型检验异常",false);

        }



        //以 . 将名字和类型分开，得到title
        if(fileNameAndType==null || !fileNameAndType.contains(".")){
            return new ResponseBodyMessage<>(0,"文件不合法，必须包含拓展名",false);
        }
        String title=fileNameAndType.substring(0,fileNameAndType.lastIndexOf("."));

        log.info("Checking if music exists: title = {}, singer = {}", title, singer);



        //判断数据库中是否有此歌曲
        Integer exist= mapper.selectByTitleAndSinger(title,singer);
        if(exist!=null && exist>0){
            return new ResponseBodyMessage<>(0,"数据库中已经存在此音乐",false);
        }


        //3..上传音乐到服务器
        String path=SAVE_PATH + fileNameAndType;
        File dest=new File(path);
        System.out.println("dest"+dest.getPath());
        if(!dest.exists()){

            dest.mkdirs();
        }
        //上传文件到目标
        try {
            file.transferTo(dest);
            log.info("服务器上传成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //将歌曲上传到数据库
        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
        String time=sf.format(new Date());

        String url="music/get?path="+title;
        User user=(User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userId=user.getId();
        try {
            int ret= mapper.insert(title,singer,time,url,userId);
            if(ret==1){
                response.sendRedirect("/list.html");
                return new ResponseBodyMessage<>(1,"数据库上传成功",true);
            }else {

                return new ResponseBodyMessage<>(-1,"数据库上传失败",false);
            }
        }catch (BindingException e){
            boolean delete= dest.delete();
            if(delete){
                log.info("数据库插入失败，已成功删除服务器上的音乐文件");
            }else{
                log.warn("数据库插入失败，未删除服务器上的音乐文件，可能需要手动删除:{}",dest.getAbsolutePath());
            }
            return new ResponseBodyMessage<>(-1,"数据库上传失败,在服务器中删除音乐",false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //播放音乐
    public ResponseEntity<byte[]> get(String path){
        File file=new File(SAVE_PATH+path);
        if(!file.exists()){
            return ResponseEntity.notFound().build();
        }
        try {
            byte[] bytes= Files.readAllBytes(file.toPath());
            HttpHeaders headers=new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(bytes.length);
            return ResponseEntity.ok().headers(headers).body(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }


    //删除音乐
    public ResponseBodyMessage<Boolean> deleteMusicById(Integer id){
        Music music=mapper.selectMusicById(id);
        if(music==null){
            return new ResponseBodyMessage<>(0,"该音乐不存在，无法删除",false);
        }
        //此时integer表示删除的行数，如果行数又0变为1则表示已经进行了删除的步骤
        Integer integer = mapper.deleteMusicById(id);
        Boolean isLoved = loveMusicMapper.selectLoveMusicByMusicId(id);
        if (isLoved != null && isLoved) {
            // 如果在收藏中，删除收藏记录
            loveMusicMapper.deleteLoveMusicByMusicId(id);
        } else {
            log.info("歌曲不在收藏音乐中");
        }
        if(integer==1){
            String title=music.getTitle();
            File file=new File(SAVE_PATH+File.separator+ title+".mp3");
            boolean delete=file.delete();

            if(delete){
                log.info("服务器中音乐删除成功");
                return new ResponseBodyMessage<>(1,"服务器中音乐删除成功",true);
            }else {
                log.error("服务器中音乐删除失败");
                return new ResponseBodyMessage<>(-1,"服务器中音乐删除失败",false);
            }
        }
        return new ResponseBodyMessage<>(-1,"音乐删除失败",false);
    }

    public ResponseBodyMessage<Boolean> deleteMusicByIdMany(List<Integer> id){
        System.out.println("所有的Id: " + id);
        int sum=0;
        for (int i = 0; i < id.size(); i++) {
            int musicId=id.get(i);
            Music music=mapper.selectMusicById(musicId);
            Boolean isLoved = loveMusicMapper.selectLoveMusicByMusicId(musicId);
            if (isLoved != null && isLoved) {
                // 如果在收藏中，删除收藏记录
                loveMusicMapper.deleteLoveMusicByMusicId(musicId);
            } else {
                log.info("歌曲不在收藏音乐中");
            }
            System.out.println("当前正在处理的 ID: " + id);
            if(music==null){
                log.error("该歌曲不存在");
                continue;
            }
            //此时integer表示删除的行数，如果行数又0变为1则表示已经进行了删除的步骤
            Integer integer = mapper.deleteMusicById(musicId);
            if(integer==1){
                String title=music.getTitle();
                File file=new File(SAVE_PATH+File.separator+ title+".mp3");
                boolean delete=file.delete();
                if(delete){
                    sum+=integer;
                    log.info("服务器中音乐删除成功");
                }else {
                    log.error("服务器中音乐删除失败");
                }
            }else {
                log.error("数据库删除失败");
            }
        }
        if(sum==id.size()){
            log.info("批量删除成功");
            return new ResponseBodyMessage<>(1,"服务器中音乐批量删除成功",true);
        }else {
            log.info("批量删除失败");
            return new ResponseBodyMessage<>(-1,"服务器中音乐批量删除失败",false);
        }
    }

    public ResponseBodyMessage<List<Music>> findMusic(String musicName){
        List<Music> musics=null;
        //musicName!=null是判断传入的歌曲名是否为空
        //musicName.trim().isEmpty()是去掉前后的空格，判断字符串是否为空，加上这个更加的严谨
        if(musicName!=null && !musicName.trim().isEmpty()){
            log.info("已找到该歌曲");
            musics=mapper.findMusicByTitle(musicName);
            if(musics.isEmpty()){
                return new ResponseBodyMessage<>(-1,"没有找到该歌曲",musics);
            }
            return new ResponseBodyMessage<>(1,"成功找到该歌曲",musics);
        }else {
            log.info("找到全部的歌曲");
            musics=mapper.findMusic();
            return new ResponseBodyMessage<>(1,"成功找到全部的歌曲",musics);
        }
    }

}
